// 游戏配置
const config = {
    rows: 20,
    cols: 10,
    cellSize: 30,
    colors: {
        empty: '#1a1a1a',
        border: '#333',
        tetromino: [
            '#3ABFF8', // I
            '#165DFF', // J
            '#FBBD23', // L
            '#F87272', // O
            '#36D399', // S
            '#8B5CF6', // T
            '#F43F5E'  // Z
        ]
    },
    speeds: [1000, 800, 600, 400, 300] // 等级1 - 5对应的下落速度
};

// 方块形状定义（7种基础俄罗斯方块形状）
const SHAPES = [
    [[1, 1, 1, 1]],          // I型
    [[1, 0, 0], [1, 1, 1]],  // J型
    [[0, 0, 1], [1, 1, 1]],  // L型
    [[1, 1], [1, 1]],        // O型
    [[0, 1, 1], [1, 1, 0]],  // S型
    [[0, 1, 0], [1, 1, 1]],  // T型
    [[1, 1, 0], [0, 1, 1]]   // Z型
];

class TetrisGame {
    constructor() {
        // 初始化画布和上下文
        this.canvas = document.getElementById('game-canvas');
        this.ctx = this.canvas.getContext('2d');

        // 游戏状态
        this.board = this.createEmptyBoard();
        this.currentPiece = this.newPiece();
        this.nextPiece = this.newPiece();
        this.score = 0;
        this.level = 1;
        this.isGameOver = false;
        this.isPaused = true;
        this.dropInterval = config.speeds[0];
        this.lastDropTime = 0;

        // DOM元素引用
        this.scoreDisplay = document.getElementById('score');
        this.levelDisplay = document.getElementById('level');
        this.overlay = document.getElementById('overlay');
        this.overlayText = document.getElementById('overlay-text');
        this.overlayBtn = document.getElementById('overlay-button');
        this.currentPreview = document.getElementById('current-preview');
        this.nextPreview = document.getElementById('next-preview');
        this.skillDisplay = document.getElementById('skill-display');

        // 初始状态设置
        this.overlay.style.display = 'flex';
        this.bindEvents();
        this.startLoop();
    }

    // 创建空棋盘
    createEmptyBoard() {
        return Array(config.rows).fill(null).map(() =>
            Array(config.cols).fill(0)
        );
    }

    // 生成新方块
    newPiece() {
        const type = Math.floor(Math.random() * SHAPES.length);
        const shape = SHAPES[type];
        return {
            type,
            shape,
            color: type + 1,
            x: Math.floor((config.cols - shape[0].length) / 2),
            y: 0
        };
    }

    // 绑定所有事件
    bindEvents() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.handleKey(e);
            e.preventDefault(); // 阻止默认滚动行为
        });

        // 按钮事件
        document.getElementById('left-btn').addEventListener('click', () => this.move(-1));
        document.getElementById('right-btn').addEventListener('click', () => this.move(1));
        document.getElementById('down-btn').addEventListener('click', () => this.drop());
        document.getElementById('rotate-btn').addEventListener('click', () => this.rotate());
        document.getElementById('drop-btn').addEventListener('click', () => this.hardDrop());
        document.getElementById('pause-btn').addEventListener('click', () => this.togglePause());
        this.overlayBtn.addEventListener('click', () => this.toggleGameState());
    }

    // 游戏主循环
    startLoop() {
        requestAnimationFrame((timestamp) => this.update(timestamp));
    }

    // 更新游戏状态
    update(timestamp) {
        if (this.isGameOver || this.isPaused) return requestAnimationFrame(this.startLoop.bind(this));

        // 自动下落逻辑
        if (timestamp - this.lastDropTime >= this.dropInterval) {
            this.drop();
            this.lastDropTime = timestamp;
        }

        this.render();
        requestAnimationFrame(this.update.bind(this));
    }

    // 渲染游戏画面
    render() {
        this.drawBackground();
        this.drawGrid();
        this.drawFixedBlocks();
        this.drawActivePiece();
        this.updatePreviews();
    }

    // 绘制背景
    drawBackground() {
        this.ctx.fillStyle = config.colors.empty;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }

    // 绘制网格线
    drawGrid() {
        this.ctx.strokeStyle = config.colors.border;
        this.ctx.lineWidth = 1;

        // 水平线
        for (let y = 0; y <= config.rows; y++) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y * config.cellSize);
            this.ctx.lineTo(this.canvas.width, y * config.cellSize);
            this.ctx.stroke();
        }

        // 垂直线
        for (let x = 0; x <= config.cols; x++) {
            this.ctx.beginPath();
            this.ctx.moveTo(x * config.cellSize, 0);
            this.ctx.lineTo(x * config.cellSize, this.canvas.height);
            this.ctx.stroke();
        }
    }

    // 绘制固定方块
    drawFixedBlocks() {
        this.board.forEach((row, y) => {
            row.forEach((cell, x) => {
                if (cell) this.drawBlock(x, y, cell);
            });
        });
    }

    // 绘制当前活动方块
    drawActivePiece() {
        const { shape, x, y, color } = this.currentPiece;
        shape.forEach((row, dy) => {
            row.forEach((cell, dx) => {
                if (cell) this.drawBlock(x + dx, y + dy, color);
            });
        });
    }

    // 绘制单个方块
    drawBlock(x, y, color) {
        const size = config.cellSize - 1;
        const [r, g, b] = this.hexToRgb(config.colors.tetromino[color - 1]);

        // 填充颜色
        this.ctx.fillStyle = config.colors.tetromino[color - 1];
        this.ctx.fillRect(x * config.cellSize, y * config.cellSize, size, size);

        // 高光效果
        this.ctx.fillStyle = `rgba(${r}, ${g}, ${b}, 0.3)`;
        this.ctx.fillRect(x * config.cellSize, y * config.cellSize, size / 2, size / 2);
    }

    // 移动方块（dir: -1左移, 1右移）
    move(dir) {
        const newX = this.currentPiece.x + dir;
        if (!this.checkCollision({ ...this.currentPiece, x: newX })) {
            this.currentPiece.x = newX;
            this.render();
        }
    }

    // 下落方块
    drop() {
        const newY = this.currentPiece.y + 1;
        if (!this.checkCollision({ ...this.currentPiece, y: newY })) {
            this.currentPiece.y = newY;
            this.render();
        } else {
            this.lockPiece();
            this.clearLines();
            this.switchPieces();
            this.checkGameOver();
        }
    }

    // 直接下落到底
    hardDrop() {
        while (!this.checkCollision({ ...this.currentPiece, y: this.currentPiece.y + 1 })) {
            this.currentPiece.y++;
        }
        this.lockPiece();
        this.clearLines();
        this.switchPieces();
        this.checkGameOver();
        this.render();
    }

    // 旋转方块
    rotate() {
        const originalShape = [...this.currentPiece.shape];
        const rotatedShape = originalShape[0].map((_, col) =>
            originalShape.map(row => row[col]).reverse()
        );

        if (!this.checkCollision({ ...this.currentPiece, shape: rotatedShape })) {
            this.currentPiece.shape = rotatedShape;
            this.render();
        } else {
            // 尝试水平移动后旋转（处理墙踢逻辑）
            const offset = [-1, 0, 1];
            for (const off of offset) {
                const testPiece = {
                    ...this.currentPiece,
                    shape: rotatedShape,
                    x: this.currentPiece.x + off
                };
                if (!this.checkCollision(testPiece)) {
                    this.currentPiece = testPiece;
                    this.render();
                    return;
                }
            }
            this.currentPiece.shape = originalShape; // 最终无法旋转则回退
        }
    }

    // 检查碰撞
    checkCollision(piece) {
        const { shape, x, y } = piece || this.currentPiece;
        return shape.some((row, dy) =>
            row.some((cell, dx) => {
                if (!cell) return false;
                const posX = x + dx;
                const posY = y + dy;
                return (
                    posX < 0 ||
                    posX >= config.cols ||
                    posY >= config.rows ||
                    (posY >= 0 && this.board[posY][posX])
                );
            })
        );
    }

    // 锁定方块到棋盘
    lockPiece() {
        const { shape, x, y, color } = this.currentPiece;
        shape.forEach((row, dy) => {
            row.forEach((cell, dx) => {
                if (cell && y + dy >= 0) {
                    this.board[y + dy][x + dx] = color;
                }
            });
        });
    }

    // 消除满行
    clearLines() {
        const originalLength = this.board.length;
        this.board = this.board.filter(row => !row.every(cell => cell));
        const lines = originalLength - this.board.length;

        // 补充空行
        for (let i = 0; i < lines; i++) {
            this.board.unshift(Array(config.cols).fill(0));
        }

        if (lines > 0) {
            this.calculateScore(lines);
        }
    }

    // 计算得分
    calculateScore(lines) {
        const scoreTable = [0, 100, 300, 500, 800]; // 对应1 - 4行消除得分
        this.score += scoreTable[lines] * this.level;
        this.scoreDisplay.textContent = this.score;

        // 更新等级
        const newLevel = Math.floor(this.score / 1000) + 1;
        if (newLevel !== this.level) {
            this.level = newLevel;
            this.levelDisplay.textContent = this.level;
            this.dropInterval = config.speeds[Math.min(this.level - 1, config.speeds.length - 1)];
        }
    }

    // 切换当前方块和下一个方块
    switchPieces() {
        this.currentPiece = this.nextPiece;
        this.nextPiece = this.newPiece();
        this.updatePreviews();
    }

    // 检查游戏是否结束
    checkGameOver() {
        if (this.checkCollision(this.currentPiece)) {
            this.isGameOver = true;
            this.overlayText.textContent = '游戏结束！得分：' + this.score;
            this.overlayBtn.textContent = '重新开始';
            this.overlay.style.display = 'flex';
        }
    }

    // 切换游戏状态（开始/暂停/继续）
    toggleGameState() {
        if (this.isGameOver) {
            this.resetGame();
        } else {
            this.isPaused = !this.isPaused;
            this.overlay.style.display = this.isPaused ? 'flex' : 'none';
            if (!this.isPaused) this.lastDropTime = performance.now();
        }
    }

    // 重置游戏
    resetGame() {
        this.board = this.createEmptyBoard();
        this.currentPiece = this.newPiece();
        this.nextPiece = this.newPiece();
        this.score = 0;
        this.level = 1;
        this.isGameOver = false;
        this.isPaused = false;
        this.dropInterval = config.speeds[0];
        this.scoreDisplay.textContent = 0;
        this.levelDisplay.textContent = 1;
        this.overlay.style.display = 'none';
        this.skillAvailable = false;
        this.skillDisplay.textContent = '';
    }

    // 按键处理
    handleKey(e) {
        switch (e.key) {
            case 'ArrowLeft':
                this.move(-1);
                break;
            case 'ArrowRight':
                this.move(1);
                break;
            case 'ArrowDown':
                this.drop();
                break;
            case 'ArrowUp':
                this.rotate();
                break;
            case ' ':
                this.hardDrop();
                break;
            case 'p':
            case 'P':
                this.togglePause();
                break;
        }
    }

    // 更新预览窗口
    updatePreviews() {
        this.renderPreview(this.currentPiece, this.currentPreview, '当前方块');
        this.renderPreview(this.nextPiece, this.nextPreview, '下一个方块');
    }

    // 渲染预览画面
    renderPreview(piece, container, title) {
        container.innerHTML = '';
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const size = 30; // 预览方块大小
        const rows = piece.shape.length;
        const cols = piece.shape[0].length;
        const maxDim = Math.max(rows, cols);
        canvas.width = maxDim * size;
        canvas.height = (maxDim + 1) * size; // 预留标题空间

        // 绘制标题
        ctx.font = '12px Arial';
        ctx.fillStyle = '#333';
        ctx.fillText(title, 5, 15);

        // 绘制方块
        piece.shape.forEach((row, y) => {
            row.forEach((cell, x) => {
                if (cell) {
                    const xPos = ((maxDim - cols) / 2 + x) * size;
                    const yPos = ((maxDim - rows) / 2 + y) * size + size;
                    ctx.fillStyle = config.colors.tetromino[piece.color - 1];
                    ctx.fillRect(xPos, yPos, size - 2, size - 2);
                    ctx.strokeStyle = '#666';
                    ctx.strokeRect(xPos, yPos, size - 2, size - 2);
                }
            });
        });

        container.appendChild(canvas);
    }

    // 十六进制颜色转RGB
    hexToRgb(hex) {
        const r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);
        return [r, g, b];
    }

    // 使用技能

    // 暂停游戏
    togglePause() {
        this.isPaused = !this.isPaused;
        this.overlay.style.display = this.isPaused ? 'flex' : 'none';
        if (!this.isPaused) this.lastDropTime = performance.now();
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => new TetrisGame());